<template>
  <view>
    <view class="nav-wrap">
      <u-icon
        class="icon"
        color="rgb(0, 0, 0)"
        size="20"
        name="arrow-left"
        @click="goback"
      ></u-icon>
      <view class="tit">添加病历</view>
      <view
        class="btn"
        v-if="isDisabledInput"
        @click="() => changeDisabledStatus(false)"
      >
        编辑
      </view>
      <view class="btn" v-else @click="submit">提交</view>
    </view>
    <view class="medical-record-wrap box-wrap">
      <view class="medical-record-row title">
        <text class="medical-record-cell text-key cell-border">
          {{ MedicalRecordText[MedicalRecordKeys.PatientName] }}
        </text>
        <text class="medical-record-cell text-val cell-border">
          {{ medicalRecord[MedicalRecordKeys.PatientName] }}
        </text>
      </view>
      <view class="medical-record-row title">
        <text class="medical-record-cell text-key cell-border">
          {{ MedicalRecordText[MedicalRecordKeys.PatientCaseType] }}
        </text>
        <text class="medical-record-cell text-val cell-border">
          <view
            class="wrap"
            @click="() => togglePicker(true, MedicalRecordKeys.PatientCaseType)"
          >
            <view class="item-left">
              <input
                disabled
                type="text"
                class="input-font"
                :value="
                  PatientCaseTypeText[
                    medicalRecord[MedicalRecordKeys.PatientCaseType]
                  ]
                "
              />
            </view>
            <view class="item-right">
              <u-icon
                color="rgb(0, 0, 0)"
                size="20"
                name="arrow-right"
              ></u-icon>
            </view>
          </view>
        </text>
      </view>
      <view class="medical-record-row title">
        <text class="medical-record-cell text-key cell-border">
          {{ MedicalRecordText[MedicalRecordKeys.VisitState] }}
        </text>
        <text class="medical-record-cell text-val cell-border">
          <view
            class="wrap"
            @click="() => togglePicker(true, MedicalRecordKeys.VisitState)"
          >
            <view class="item-left">
              <input
                disabled
                class="input-font"
                type="text"
                :value="
                  DiagnosisStatusText[
                    medicalRecord[MedicalRecordKeys.VisitState]
                  ]
                "
              />
            </view>
            <view class="item-right">
              <u-icon
                color="rgb(0, 0, 0)"
                size="20"
                name="arrow-right"
              ></u-icon>
            </view>
          </view>
        </text>
      </view>
      <view class="medical-record-row title">
        <text class="medical-record-cell text-key cell-border">
          {{ MedicalRecordText[MedicalRecordKeys.DiagnosisTime] }}
        </text>
        <text class="medical-record-cell text-val cell-border">
          <uni-datetime-picker
            :disabled="isDisabledInput"
            :clear-icon="false"
            type="date"
            placeholder="请选择就诊时间"
            :border="false"
            :value="medicalRecord[MedicalRecordKeys.DiagnosisTime]"
            end="2029-6-20"
            @change="changeDiagnosisTime"
          >
            <view class="wrap">
              <view class="item-left">
                <input
                  disabled
                  type="text"
                  class="input-font"
                  placeholder="请选择就诊时间"
                  :value="medicalRecord[MedicalRecordKeys.DiagnosisTime]"
                />
              </view>
              <view class="item-right">
                <u-icon
                  color="rgb(0, 0, 0)"
                  size="20"
                  name="arrow-right"
                ></u-icon>
              </view>
            </view>
          </uni-datetime-picker>
        </text>
      </view>
      <view class="medical-record-row title">
        <text class="medical-record-cell text-key cell-border">
          {{ MedicalRecordText[MedicalRecordKeys.Hospital] }}
        </text>
        <view class="medical-record-cell text-val cell-border">
          <view
            class="wrap"
            @click="() => togglePicker(true, MedicalRecordKeys.Hospital)"
          >
            <view class="item-left">
              <input
                disabled
                type="text"
                class="input-font"
                placeholder="请选择就诊医院"
                :value="medicalRecord[MedicalRecordKeys.Hospital].title"
              />
            </view>
            <view class="item-right">
              <u-icon
                color="rgb(0, 0, 0)"
                size="20"
                name="arrow-right"
              ></u-icon>
            </view>
          </view>
        </view>
      </view>
      <view class="medical-record-row title">
        <text class="medical-record-cell text-key cell-border">
          {{ MedicalRecordText[MedicalRecordKeys.Department] }}
        </text>
        <text class="medical-record-cell text-val cell-border">
          <view
            class="wrap"
            @click="() => togglePicker(true, MedicalRecordKeys.Department)"
          >
            <view class="item-left">
              <input
                disabled
                class="input-font"
                type="text"
                placeholder="请选择就诊科室"
                :value="medicalRecord[MedicalRecordKeys.Department].title"
              />
            </view>
            <view class="item-right">
              <u-icon
                color="rgb(0, 0, 0)"
                size="20"
                name="arrow-right"
              ></u-icon>
            </view>
          </view>
        </text>
      </view>
      <view class="medical-record-row title">
        <text class="medical-record-cell text-key">
          {{ MedicalRecordText[MedicalRecordKeys.DoctorName] }}
        </text>
        <text class="medical-record-cell text-val">
          <input
            :disabled="isDisabledInput"
            type="text"
            class="input-font"
            placeholder="请填写"
            v-model="medicalRecord[MedicalRecordKeys.DoctorName]"
          />
        </text>
      </view>
    </view>
    <view class="box-wrap remarks">
      <view class="title">
        {{ MedicalRecordText[MedicalRecordKeys.remarks] }}
      </view>
      <input
        class="input-font"
        type="text"
        :disabled="isDisabledInput"
        placeholder="请填写"
        v-model="medicalRecord[MedicalRecordKeys.remarks]"
      />
    </view>
    <view class="box-wrap">
      <view class="title">
        {{ MedicalRecordText[MedicalRecordKeys.IllnessDescribe] }}
      </view>
      <input
        class="input-font"
        type="text"
        :disabled="isDisabledInput"
        placeholder="请填写"
        v-model="medicalRecord[MedicalRecordKeys.IllnessDescribe]"
      />
    </view>
    <view class="box-wrap">
      <view class="title">
        {{ MedicalRecordText[MedicalRecordKeys.AffectedPartImg] }}
      </view>
      <view class="image-upload">
        <u-upload
          :disabled="isDisabledInput"
          maxCount="9"
          width="200rpx"
          height="200rpx"
          name="1"
          previewImage
          imageMode="aspectFill"
          :fileList="medicalRecord[MedicalRecordKeys.AffectedPartImg]"
          @delete="deletePic($event, MedicalRecordKeys.AffectedPartImg)"
          @afterRead="uploadPic($event, MedicalRecordKeys.AffectedPartImg)"
        />
      </view>
    </view>
    <view class="box-wrap">
      <view class="title">
        {{ MedicalRecordText[MedicalRecordKeys.DiagnosticOpinion] }}
      </view>
      <input
        class="input-font"
        disabled
        type="text"
        :value="medicalRecord[MedicalRecordKeys.DiagnosticOpinion]"
      />
    </view>
    <u-picker
      keyName="text"
      closeOnClickOverlay
      :show="isShowPicker"
      :columns="pickerData"
      @confirm="confirmPicker"
      @cancel="() => togglePicker(false)"
    />
  </view>
</template>

<script>
  import {
    UserKeys,
    PageState,
    defaultRecord,
    MedicalRecordKeys,
    MedicalRecordText,
    DiagnosisStatusList,
    DiagnosisStatusText,
    PatientCaseTypeList,
    PatientCaseTypeText,
    MedicalRecordCheckList,
  } from "../helper";
  import healthRecords from "@/api/healthRecords";
  import hospitalUrl from "@/api/expertConsulation";
  import { getStorage } from "@/utils/cookies.js";
  import { uploadUrl } from "@/utils/request.js";

  export default {
    components: {},

    props: {
      record: {
        type: Object,
        default: {},
      },
      user: {
        type: Object,
        default: {},
      },
      goback: {
        type: Function,
        default: () => {},
      },
      pageState: {
        type: String,
        default: PageState.AddRecord,
      },
    },

    data() {
      return {
        isShowPicker: false,
        pickerData: [],
        medicalRecord: { ...defaultRecord },
        latitude: 30,
        longitude: 30,
        disabled: false,
      };
    },

    created() {
      if (this.pageState === PageState.AddRecord) {
        this.medicalRecord[MedicalRecordKeys.PatientName] =
          this.user[UserKeys.Name];
      } else {
        this.medicalRecord = {
          ...this.record,
          [MedicalRecordKeys.AffectedPartImg]: Array.isArray(
            this.record[MedicalRecordKeys.AffectedPartImg]
          )
            ? this.record[MedicalRecordKeys.AffectedPartImg]
            : [],
        };
        this.disabled = true;
      }
      uni.getLocation({
        type: "gcj02",
        success: ({ longitude, latitude }) => {
          this.latitude = latitude;
          this.longitude = longitude;
        },
        complete: (res) => {},
      });
    },

    methods: {
      changeDisabledStatus(disabled) {
        this.disabled = disabled;
      },

      changeDiagnosisTime(ymt) {
        this.medicalRecord[MedicalRecordKeys.DiagnosisTime] = ymt;
      },

      confirmPicker({ value: [item] }) {
        if (
          item.key === MedicalRecordKeys.Hospital ||
          item.key === MedicalRecordKeys.Department
        ) {
          this.medicalRecord[item.key] = item;
        } else {
          this.medicalRecord[item.key] = item.id;
        }
        this.isShowPicker = false;
      },

      togglePicker(isShowPicker, key) {
        if (isShowPicker) {
          if (this.isDisabledInput) {
            return;
          }
          this.formatePickerData(key);
        } else {
          this.isShowPicker = isShowPicker;
        }
      },

      formatePickerData(key) {
        if (key === MedicalRecordKeys.VisitState) {
          this.pickerData = [
            DiagnosisStatusList.map((item) => {
              return {
                key,
                id: item,
                text: DiagnosisStatusText[item],
              };
            }),
          ];
          this.isShowPicker = true;
        } else if (key === MedicalRecordKeys.PatientCaseType) {
          this.pickerData = [
            PatientCaseTypeList.map((item) => {
              return {
                key,
                id: item,
                text: PatientCaseTypeText[item],
              };
            }),
          ];
          this.isShowPicker = true;
        } else if (key === MedicalRecordKeys.Hospital) {
          this.$axios({
            url: hospitalUrl.getHospitalList,
            data: {
              lng: this.longitude,
              lat: this.latitude,
            },
          }).then((res) => {
            this.pickerData = [
              res.data.arr.data.map((item) => {
                return {
                  ...item,
                  text: item.title,
                  key,
                };
              }),
            ];
            this.isShowPicker = true;
          });
        } else if (key === MedicalRecordKeys.Department) {
          this.$axios({
            url: healthRecords.section,
            data: {
              hospital_id: this.medicalRecord[MedicalRecordKeys.Hospital].id,
            },
          }).then((res) => {
            this.pickerData = [
              res.data.list.map((item) => {
                return {
                  ...item,
                  key,
                };
              }),
            ];
            this.isShowPicker = true;
          });
        }
      },

      uploadPic(e, key) {
        const apiurl = uploadUrl("/api/upload_img");
        uni.uploadFile({
          url: apiurl,
          filePath: e.file.thumb,
          name: "file",
          header: {
            Authorized: getStorage(),
          },
          success: (res) => {
            if (res.statusCode === 200) {
              const {
                data: { url },
              } = JSON.parse(res.data);
              this.medicalRecord[key].push({ url });
            } else {
              this.$u.toast("图片上传失败，请重试");
            }
          },
          fail: (err) => {
            this.$u.toast(err.errMsg);
            this.medicalRecord[key].pop();
          },
        });
      },

      deletePic(e, key) {
        this.medicalRecord[key].pop();
      },

      submit() {
        let emptyKey = "";
        if (
          MedicalRecordCheckList.some((key) => {
            emptyKey = key;
            if (
              [
                MedicalRecordKeys.Hospital,
                MedicalRecordKeys.Department,
              ].includes(key)
            ) {
              return !this.medicalRecord[key].title;
            }
            return this.medicalRecord[key] === "";
          })
        ) {
          this.$u.toast(
            (emptyKey === MedicalRecordKeys.DoctorName ? "请输入" : "请选择") +
              MedicalRecordText[emptyKey]
          );
          return;
        }
        const payload = {
          ...this.medicalRecord,
          [MedicalRecordKeys.AffectedPartImg]: this.medicalRecord[
            MedicalRecordKeys.AffectedPartImg
          ].map((item) => item.url),
          hospital_id: this.medicalRecord[MedicalRecordKeys.Hospital].id,
          section_id: this.medicalRecord[MedicalRecordKeys.Department].id,
        };
        delete payload[MedicalRecordKeys.Hospital];
        delete payload[MedicalRecordKeys.Department];
        this.$axios({
          url: healthRecords.addPatientCase,
          method: "POST",
          data: payload,
        }).then((res) => {});
      },
    },

    computed: {
      PageState: function () {
        return PageState;
      },
      MedicalRecordKeys: function () {
        return MedicalRecordKeys;
      },
      MedicalRecordText: function () {
        return MedicalRecordText;
      },
      DiagnosisStatusText: function () {
        return DiagnosisStatusText;
      },
      PatientCaseTypeText: function () {
        return PatientCaseTypeText;
      },
      isDisabledInput: function () {
        return this.pageState === PageState.ModifyRecord && this.disabled;
      },
      img: function () {
        if (PageState.AddRecord === this.pageState) {
          return null;
        }
        return [
          {
            url: this.record[MedicalRecordKeys.AffectedPartImg].replace(
              "blob:",
              ""
            ),
          },
        ];
      },
    },
  };
</script>

<style lang="scss" scoped>
  .nav-wrap {
    height: 87rpx;
    background: $uni-bg-color;
    line-height: 87rpx;
    display: table;
    width: 750rpx;

    & .icon {
      display: table-cell;
      width: 70rpx;
      padding-left: 20rpx;
    }

    & .tit {
      display: table-cell;
      text-align: center;
      height: 87rpx;
      font-size: 32rpx;
      line-height: 87rpx;
      font-weight: bold;
    }

    & .btn {
      display: table-cell;
      font-weight: bold;
      width: 80rpx;
    }
  }

  .box-wrap {
    background: $uni-bg-color;
    padding: 0 20rpx 20rpx 20rpx;
  }

  .title {
    line-height: 100rpx;
    font-weight: bold;
  }

  .cell-border {
    border-bottom: 1rpx solid $uni-border-color;
  }

  .remarks {
    margin: 20rpx 0;
    border: none;
  }

  .image-upload {
    width: 200rpx;
    height: 200rpx;
  }

  /deep/ .input-placeholder {
    font-size: $uni-font-size-base;
  }

  .input-font {
    font-size: $uni-font-size-base;
  }

  .medical-record-wrap {
    display: table;

    & .medical-record-row {
      display: table-row;
      width: 750rpx;
      height: 100rpx;

      & .medical-record-cell {
        display: table-cell;
        width: 375rpx;
      }

      & .text-key {
        text-align: left;
      }

      & .text-val {
        text-align: right;

        & .wrap {
          display: table;

          & .item-left {
            width: 90%;
            display: table-cell;
            font-size: $uni-font-size-base;
          }

          & .item-right {
            display: table-cell;
            width: 10%;
          }
        }
      }
    }
  }
</style>
